package com.jt.utils;

import com.jt.pojo.Menu;
import com.jt.vo.MenuVo;
import io.jsonwebtoken.lang.Collections;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class MenuUtils {
    /**
     * 返回没有id的路由信息直接存入前端路由
     */
    public List<MenuVo> resultRouter(List<Menu> router) {
        List<MenuVo> returnMenuVo = new ArrayList<>();
        router.forEach(item -> {
            MenuVo menuVo = new MenuVo();
            menuVo.setName(item.getName());
            menuVo.setPath(item.getPath());
            menuVo.setComponent(item.getComponent());
            List<MenuVo> children = getChildren(item.getChildren());
            menuVo.setChildren(children);
            returnMenuVo.add(menuVo);
        });
        return returnMenuVo;
    }

    public List<MenuVo> getChildren(List<Menu> childrenList) {
        List<MenuVo> returnRouter = new ArrayList<>();
        if (!Collections.isEmpty(childrenList)) {
            childrenList.forEach(MenuOne -> {
                MenuVo menuVoChildren = new MenuVo();
                menuVoChildren.setPath(MenuOne.getPath());
                menuVoChildren.setName(MenuOne.getName());
                menuVoChildren.setComponent(MenuOne.getComponent());
                List<MenuVo> children = getChildren(MenuOne.getChildren());
                menuVoChildren.setChildren(children);
                returnRouter.add(menuVoChildren);
            });
            return returnRouter;
        } else {
            return returnRouter;
        }
    }

    /**
     * 获取菜单和子菜单
     **/
    public List<Menu> getMenuAndChildrenMenu(List<Menu> menuList) {
        List<Menu> allMenuList = menuList.stream().filter(all -> !all.getType().equals("2")).collect(Collectors.toList());
        List<Menu> oneMenuList = allMenuList.stream().filter(allMenu -> allMenu.getType().equals("0")).collect(Collectors.toList());
        setChildrenMenu(allMenuList, oneMenuList);
        return oneMenuList;
    }

    public void setChildrenMenu(List<Menu> allMenuList, List<Menu> oneMenuList) {
        oneMenuList.forEach(item -> {
            List<Menu> oneChildren = allMenuList.stream().filter(a -> a.getParentId().equals(item.getId())).collect(Collectors.toList());
            item.setChildren(oneChildren);
            setChildrenMenu(allMenuList, oneChildren);
        });
    }
}
